package com.logicbus.backend.message.tools;

import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.code.Coder;
import com.anysoft.util.code.CoderFactory;
import com.anysoft.util.code.coder.MD5;
import com.logicbus.backend.Context;
import org.apache.commons.lang3.StringUtils;

/**
 * 提取Content的md5摘要
 */
public class ContentDigest {
    protected boolean enable = true;
    protected String digestHeaderName = "Content-MD5";
    protected String digestVariableName = "$contentDigest";
    protected Coder digestCoder = null;

    public ContentDigest(Properties props){
        enable = PropertiesConstants.getBoolean(props,"http.digest",enable);
        digestHeaderName = PropertiesConstants.getString(props,"http.digest.header",digestHeaderName);
        digestVariableName = PropertiesConstants.getString(props,"http.digest.var",digestVariableName);
        try {
            digestCoder = CoderFactory.newCoder(PropertiesConstants.getString(props, "http.digest.coder", "MD5"));
        }catch(Exception ex){
            digestCoder = new MD5();
        }
    }

    public void digest(Context ctx, String data){
        if (enable && StringUtils.isNotEmpty(data)){
            String md5 = ctx.getRequestHeader(digestHeaderName);
            if (StringUtils.isNotEmpty(md5)){
                String realMd5 = digestCoder.encode(data,null);
                if (StringUtils.isNotEmpty(realMd5)){
                    ctx.SetValue(digestVariableName,realMd5);
                }
            }
        }
    }
}
